package de.koller.reason.render.obj;

import de.koller.oceanFramework.math.RVec3;
import de.koller.oceanFramework.plain.util.RRaster;
import de.koller.oceanFramework.util.ColorIntUtil;
import java.util.Random;

public class Texture extends RRaster {

	public Texture( int width, int height ) {
		super( new int[ width * height ], width, height );
	}
	
	public int nearest( float u, float v ) {
		return colorAt( texelX( u ), texelY( v ) );
	}
	
	private int texelX( float u ) {
		int x = (int)Math.floor( u * width );		
		x += width;
		x %= width;
		return x;
	}
	
	private int texelY( float v ) {
		int y = (int)Math.floor( v * height );		
		y += height;
		y %= height;
		return y;
	}
	
	private int minV( int... v ) {
		int m = v[0];
		for( int i = 1; i < v.length; i++ )
			m = Math.min( m, v[i] );
		return m;
	}
	
	private int maxV( int... v ) {
		int m = v[0];
		for( int i = 1; i < v.length; i++ )
			m = Math.max( m, v[i] );
		return m;
	}
	
	public int full( RVec3 uv0, RVec3 uv1, RVec3 uv2, RVec3 uv3 ) {
		int minTX = minV( texelX( uv0.x ), texelX( uv1.x ), texelX( uv2.x ), texelX( uv3.x ) ) + 1;
		int minTY = minV( texelY( uv0.y ), texelY( uv1.y ), texelY( uv2.y ), texelY( uv3.y ) ) + 1;
		int maxTX = maxV( texelX( uv0.x ), texelX( uv1.x ), texelX( uv2.x ), texelX( uv3.x ) ) - 1;
		int maxTY = maxV( texelY( uv0.y ), texelY( uv1.y ), texelY( uv2.y ), texelY( uv3.y ) ) - 1;
		
		int sa = 0;
		int sr = 0;
		int sg = 0;
		int sb = 0;
		int i = 0;
		
		for( int tx = minTX; tx <= maxTX; tx++ )
			for( int ty = minTY; ty <= maxTY; ty++ ) {
				i++;
				
				int c = colorAt( tx, ty );
				sa += ColorIntUtil.getAValue( c );
				sr += ColorIntUtil.getRValue( c );
				sg += ColorIntUtil.getGValue( c );
				sb += ColorIntUtil.getBValue( c );
			}
		
		if( i != 0 ) {
			sa /= i;
			sr /= i;
			sg /= i;
			sb /= i;
		}
		
		return ColorIntUtil.getIntColor( sa, sr, sg, sb );
	}
	
}
